/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {Button, Form, Icon, Modal, notification, Popconfirm, Table, Upload} from 'antd';

import {FormLayout, ModalFooter, ModalView} from 'antd-extra';
import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';

import ViewTitle from "../../../components/ViewTitle";
import styles from "../../index.less";
import ModalCreateOrEdit2 from "./ModalCreateOrEdit2";
import notify from "../../../components/NotificationExtra";

moment.locale('zh-cn');

@Form.create()
@connect(({
            tenant,
            global,
            dynamicLabel,
            dic
          }) => ({...tenant, ...dic, ...dynamicLabel, ...global}))
export default class ModalCreateOrEditDic extends FormBase {
  constructor(props) {
    super(props);
    const {record} = this.props;
    this.state = record ? {...record} : {};

  }

  componentDidMount() {
    const {table} = this.props;
    this.props.dispatch({
      type: 'global/getModel',
      payload: {table},
    });

  }

  renderFoot = () => {
    const {foot, value, callback, modalRef, record, form} = this.props;

    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }

              _.map(this.state, (item, key) => {
                values[key] = item;
              });
              values.code = record ? record.code : new Date().valueOf();
              console.log('ModalCreateOrEdit ok',values);
              callback(values);
              modalRef.close();
            });

          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };
  onEdit = (title, key, cols, record) => {
    ModalView.open(ModalCreateOrEdit2,
      {
        title,
        width: '1080px',
      }, {
        record, cols,
        callback: (payload) => {
          if (!this.state[key]) {
            this.state[key] = [];
          }
          if (record) {
            this.state[key].forEach((item, index) => {
              if (item._code === record._code) {
                this.state[key][index] = payload;
              }
            });
          } else {
            this.state[key].push(payload);
          }
          this.componentDidMount();
        }
      });
  };


  getTable = () => {
    const {table} = this.props;
    const model = this.props[`${table}Model`];
    const temp = [];
    _.map(model, (item, key) => {
      const {type, title, cols} = item;
      _.map(cols, item => {
        item.dataIndex = item.key;
        console.log('iiiii',item)
        if(item._type=== 'date'||item._type==='time'){
          item.render=(value=>{
            return <div>{moment(value).format('YYYY-MM-DD')}</div>
          })
        }
      });

      const _cols = _.cloneDeep(cols);
      const {_type = type} = item;

      if (_type === "array") {
        _cols.push(
          {
            title: "操作", key: "opt", dataIndex: "opt", fixed: 'right', width: 120, render: (value, record) => {
              return (<span>
                      {
                        <a style={{marginRight: '6px'}} disabled={record.reviewStatus === '同意'}
                           onClick={() => this.onEdit(title, key, cols, record)}>编辑</a>
                      }
                {<Popconfirm
                  title="确认删除"
                  onConfirm={() => {
                    _.remove(this.state[key], (item) => item._code === record._code);
                    this.componentDidMount();
                  }}
                  okText="是"
                  cancelText="否"
                >
                  <a style={{marginRight: '6px'}} disabled={record.reviewStatus === '同意'}>删除</a>
                </Popconfirm>}
          </span>);
            }
          }
        );
        temp.push(<div>
            <ViewTitle
              title={title}
              actions={<Button type="primary" onClick={() => {
                this.onEdit(title, key, cols);
              }}>添加</Button>}
            ></ViewTitle>
            <Table
              className={styles.antTable}
              bordered={true}
              columns={_cols}
              dataSource={this.state[key]}
              scroll={{x: true}}
              pagination={true}
              //  scroll={{x: 1300}}
            ></Table>
          </div>
        );
      }

    });
    return temp;
  };

  picHandlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
      console.log(file.preview);
    }
    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
    });
  };
  picHandleChange = ({fileList}) => {
    _.map(fileList, async file => {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj);
        //file.thumbUrl = file.response ? file.response.data : fileList.file.thumbUrl;
      }
    });
    const temp = this.state;
    temp.fileList = fileList;
    this.setState({...temp});
  };

  render() {
    const {form, table, record} = this.props;
    const model = this.props[`${table}Model`];

    _.map(model, (item, key) => {
      item.key = key;
    });
    const {fileList, previewVisible, previewImage} = this.state;
    return (
      <div>
        <FormLayout form={form} cols={2}>
          {this.getDicFields(model, record, this.state)}
        </FormLayout>
        {this.getTable()}
        {
          <div style={{marginLeft: '64px'}}>
            <Upload
              action={'http://127.0.0.1:18008/api/global/upload?type=inboundLot'} // 没有用，直接存图片流文件
              listType="picture-card"
              fileList={fileList}
              accept={".png,.jpg"}
              onPreview={this.picHandlePreview}
              onChange={this.picHandleChange}
              onDownload={file => {
                console.log('ondownlad', file);
              }}
              beforeUpload={(file, fileList) => {
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                  notify({type: 'error', message: '文件过大！'});
                  return isLt2M;
                }
                return false;
              }}
            >
              {<div>
                <Icon type="plus"/>
                <div className="ant-upload-text">上传图片</div>
              </div>}
            </Upload>
            <Modal visible={previewVisible} footer={null} onCancel={() => {
              this.setState({previewVisible: false});
            }}>
              <img alt="example" style={{width: '100%'}} src={previewImage}/>
            </Modal>
          </div>
        }
        {this.renderFoot()}
      </div>
    );
  }
}

